package com.registration.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.registration.bean.RoleBean;
import com.registration.bean.RoleMenuBean;
import com.registration.mapper.RoleMapper;
import com.registration.mapper.RoleMenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class RoleServiceImpl implements RoleService{

    @Autowired
    RoleMapper roleMapper;



    @Autowired
    RoleMenuMapper roleMenuMapper;
    @Override
    public List<RoleBean> getRoleList() {
        return roleMapper.getRoleList(new RoleBean());
    }

    @Override
    @Transactional
    public int insertRole(RoleBean roleBean) {
        int res=roleMapper.insertRole(roleBean);
        int role_id =roleBean.getRole_id();
        List<Integer> selectedMenuList =roleBean.getSelectedMenuList();
        for(Integer menu_id : selectedMenuList){
            roleMenuMapper.insertRoleMenu(new RoleMenuBean(null, role_id, menu_id));
        }
        return res;
    }

    @Override
    public int deleteRole(Integer role_id) {

        roleMenuMapper.deleteRoleMenuByRoleId(role_id);
        return roleMapper.deleteRole(role_id);
    }

    @Override
    public int updateRole(RoleBean roleBean) {
        int role_id =roleBean.getRole_id();
        List<Integer> oldList=roleMenuMapper.getMenuIdListByRoleId(role_id);
        List<Integer> newList=roleBean.getSelectedMenuList();

        for(Integer menu_id : oldList){
            if(!newList.contains(menu_id)){
                roleMenuMapper.deleteRoleMenuByRoleIdAndMenuId(role_id, menu_id);
            }
        }
        for(Integer menu_id : newList){
            if(!oldList.contains(menu_id)){
                roleMenuMapper.insertRoleMenuByRoleIdAndMenuId(role_id, menu_id);
            }
        }

        return roleMapper.updateRole(roleBean);
    }

    @Override
    public PageInfo<RoleBean> getRoleList(Integer pageNum, Integer pageSize, RoleBean roleBean) {
        PageHelper.startPage(pageNum,pageSize);
        List<RoleBean> roleBeans=roleMapper.getRoleList(roleBean);
        PageInfo<RoleBean> pageInfo=new PageInfo<>(roleBeans);
        return pageInfo;
    }
}
